import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { householdApi } from '@/api/household'

export const useHouseholdStore = defineStore('household', () => {
  // 状态
  const householdList = ref<any[]>([])
  const loading = ref(false)

  // 计算属性
  const hasHouseholds = computed(() => householdList.value.length > 0)

  // 获取房户列表
  const getHouseholdList = async (params?: any) => {
    loading.value = true
    try {
      const response = await householdApi.getHouseholdList(params)
      if (response.code === 200) {
        householdList.value = response.data || []
      } else {
        throw new Error(response.message || '获取房户列表失败')
      }
    } catch (error) {
      console.error('获取房户列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取房户详情
  const getHouseholdDetail = async (id: number) => {
    try {
      const response = await householdApi.getHouseholdDetail(id)
      if (response.code === 200) {
        return response.data
      } else {
        throw new Error(response.message || '获取房户详情失败')
      }
    } catch (error) {
      console.error('获取房户详情失败:', error)
      throw error
    }
  }

  // 重置状态
  const resetState = () => {
    householdList.value = []
    loading.value = false
  }

  return {
    // 状态
    householdList,
    loading,
    
    // 计算属性
    hasHouseholds,
    
    // 方法
    getHouseholdList,
    getHouseholdDetail,
    resetState
  }
}) 